package com.boby.homecamera.webserver.componet;

import androidx.annotation.NonNull;

import com.boby.homecamera.util.JwtUtil;
import com.yanzhenjie.andserver.annotation.Interceptor;
import com.yanzhenjie.andserver.framework.HandlerInterceptor;
import com.yanzhenjie.andserver.framework.handler.MethodHandler;
import com.yanzhenjie.andserver.framework.handler.RequestHandler;
import com.yanzhenjie.andserver.framework.mapping.Addition;
import com.yanzhenjie.andserver.http.HttpRequest;
import com.yanzhenjie.andserver.http.HttpResponse;
import com.yanzhenjie.andserver.error.HttpException;

@Interceptor
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean onIntercept(@NonNull HttpRequest request, @NonNull HttpResponse response,
                               @NonNull RequestHandler handler) {

        if (handler instanceof MethodHandler) {
            MethodHandler methodHandler = (MethodHandler) handler;
            Addition addition = methodHandler.getAddition();

            if (isNeedLogin(addition)) {
                String token = request.getHeader("Authorization");
                if (token == null || !token.startsWith("Bearer ")) {
                    throw new HttpException(401, "Missing or invalid Authorization header.");
                }

                token = token.substring(7); // 移除 "Bearer " 前缀
                String user = JwtUtil.INSTANCE.validateToken(token);
                if(user == null){
                    throw new HttpException(401, "Invalid or expired token.");
                }
                // 可将用户信息放入 request 中
                request.setAttribute("user", user);
            }
        }

        return false; // false 表示继续请求执行链
    }

    //只对带有 @Addition(stringType = ["login"], booleanType = [true]) 的接口启用 token 校验；
    //无 token 或 token 非法会返回 401；
    //校验成功可通过 request.getAttribute("user") 获取用户名。
    private boolean isNeedLogin(Addition addition) {
        if (addition == null) return false;

        String[] stringType = addition.getStringType();
        if (stringType == null || stringType.length == 0) return false;

        boolean[] booleanType = addition.getBooleanType();
        if (booleanType == null || booleanType.length == 0) return false;

        return "login".equalsIgnoreCase(stringType[0]) && booleanType[0];
    }
}
